<?php
namespace addons\paotui\service;

use app\admin\model\paotui\Config;
use app\admin\model\paotui\TemplateIds;
use app\admin\model\paotui\Third;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;

/**
 * 用户端模板消息
 * Class SendTemplate
 * @package app\common\service
 */
class SendTemplate{
    public $error;
    public $templateIds;

    public function __construct()
    {
        $templateIdsModel = new TemplateIds();
        $templateIdsList = $templateIdsModel->column("code,template_id");
        $this->templateIds = $templateIdsList;
    }

    /**
     * 创建送达通知
     */
    public function create_post_reach($postInfo){

        $user_id = $postInfo['user_id'];
        // $wechatUser = Third::get(['user_id'=>$user_id]);
        $wechatUser = db('shopro_third_oauth')->where(['user_id'=>$user_id])->find();

        $templateIdsModel = new TemplateIds();
        $templateIdsInfo = $templateIdsModel->where(['code'=>'post_reach'])->find();
        $content = json_decode($templateIdsInfo['content'],true);
		
		$sdxx=$postInfo['to_name']." ".$postInfo['to_mobile'];
		if(!$postInfo['to_name'] || !$postInfo['to_mobile']){
			$addinfo=db('shopro_user_address')->where('id',$postInfo['to_address_id'])->find();
			$sdxx=$addinfo['consignee']." ".$addinfo['mobile'];
		}


        $msg = [
            'touser'=>$wechatUser['openid'],
            'template_id'=>$templateIdsInfo['template_id'],
            // 'page'=>'pages/voucher/index?order_no='.$postInfo['order_no'],
            'page'=>'paotui/voucher/index?order_no='.$postInfo['order_no'],
            'lang'=>'zh_CN',
            'data'=>[
                $content['keyword1']['field']=>$postInfo['order_no'],
                $content['keyword2']['field']=>['value'=>date("Y-m-d H:i:s",$postInfo['completetime'])],
                $content['keyword3']['field']=>['value'=>$sdxx],
            ]
        ];

        //添加到数据库
        $sendTemplateModel = new \app\admin\model\paotui\SendTemplate();
        $sendTemplateModel->save([
            'type'=>1,
            'msg'=>json_encode($msg)
        ]);
    }

    /**
     * 快递员接单
     */
    public function create_receive_post($postInfo){
        $user_id = $postInfo['user_id'];
        // $wechatUser = Third::get(['user_id'=>$user_id]);
        $wechatUser = db('shopro_third_oauth')->where(['user_id'=>$user_id])->find();

        $templateIdsModel = new TemplateIds();
        $templateIdsInfo = $templateIdsModel->where(['code'=>'receive_post'])->find();
        $content = json_decode($templateIdsInfo['content'],true);
		
		$sjxx=$postInfo['to_name']." ".$postInfo['to_mobile'];
		if(!$postInfo['to_name'] || !$postInfo['to_mobile']){
			$addinfo=db('shopro_user_address')->where('id',$postInfo['to_address_id'])->find();
			$sjxx=$addinfo['consignee']." ".$addinfo['mobile'];
		}

        $msg = [
            'touser'=>$wechatUser['openid'],
            'template_id'=>$this->templateIds['receive_post'],
            // 'page'=>'pages/voucher/index?order_no='.$postInfo['order_no'],
            'page'=>'paotui/voucher/index?order_no='.$postInfo['order_no'],
            'lang'=>'zh_CN',
            'data'=>[
                $content['keyword1']['field']=>['value'=>$postInfo['order_no']],
                $content['keyword2']['field']=>['value'=>$postInfo['pay_price']],
                $content['keyword3']['field']=>['value'=>"收件信息："],
                'thing15'=>['value'=>$sjxx],
            ]
        ];

        //添加到数据库
        $sendTemplateModel = new \app\admin\model\paotui\SendTemplate();
        $sendTemplateModel->save([
            'type'=>1,
            'msg'=>json_encode($msg)
        ]);
    }

    public static function send(){
     
        $sendTemplateModel = new \app\admin\model\paotui\SendTemplate();
        $tmpl = $sendTemplateModel->where(['status'=>0])->order("id asc")->find();
        if($tmpl){

            $configModel = new Config();
            $config = $configModel->where(['group'=>'mini'])->column("name,value");

            $options = [
                'app_id'   => $config['mini_appid'],
                'secret'   => $config['mini_appsecret'],
                'log' => [
                    'default' => 'prod', // 默认使用的 channel，生产环境可以改为下面的 prod
                    'channels' => [
                        // 测试环境
                        'dev' => [
                            'driver' => 'single',
                            'path' => '/tmp/logs/easywechat.log',
                            'level' => 'debug',
                        ],
                        // 生产环境
                        'prod' => [
                            'driver' => 'daily',
                            'path' => '/tmp/logs/easywechat.log',
                            'level' => 'error',
                        ],
                    ],
                ],
            ];

            $app = Factory::miniProgram($options);

            try {
                $result = $app->subscribe_message->send(json_decode($tmpl['msg'],true));
                $errmsg = $result['errmsg'];
            }catch (Exception $e){
                $errmsg = $e->getMessage();
            }

            $tmpl->save(['status'=>1,'sendtime'=>time(),'errmsg'=>$errmsg]);
        }
    }
}